<!-- 题目管理 -->
<script setup lang="ts">
import { ref } from "vue"
import { ElUpload, ElButton } from "element-plus"
import type { UploadProps } from 'element-plus'
import { obsUpload, obsDownload } from "#/utils/obs"

const file = ref<any>(null);
const status = ref<string>('');

const submitUpload = () => {
  // 读取文件内容
  const reader = new FileReader();
  reader.onload = function (event) {
    // const arrayBuffer = event.target?.result as ArrayBuffer;
    // 上传文件
    obsUpload({
      Key: file.value.name,
      SourceFile: file.value
    }, (err: any, result: any) => {
      if (err) {
        console.error('Error:', err);
        status.value = 'Upload failed: ' + JSON.stringify(err);
        return;
      }

      console.log('Result:', result);
      status.value = 'File uploaded successfully!';
    });
  };

  reader.onerror = function (event) {
    console.error('File could not be read:', event);
    status.value = 'Failed to read file.';
  };

  reader.readAsArrayBuffer(file.value);
}
const handleUpload: any = (options: any) => {
  console.log(options)
  file.value = options.file;
}

const download = () => {
  //https://dev-edu-obs.obs.cn-north-4.myhuaweicloud.com/edu/screenshot-20250510-211110.png
  obsDownload({
    Key: `edu/screenshot-20250510-211110.png`,
  },(err: any, result: any) => {
      if (err) {
        console.error('获取失败:', err);
        return;
      }
      // 创建Blob对象并触发下载
      const blob = new Blob([result.InterfaceResult.Content]);
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'screenshot-20250510-211110.png'; // 可自定义下载文件名
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url); // 清理内存
    })
}

</script>
<template>
  <div class="topocs m-[100px]">
    <el-upload class="upload-demo" action="#" :http-request="handleUpload" :auto-upload="true" :show-file-list="false">
      <template #trigger>
        <el-button slot="trigger" type="primary">Select File</el-button>
      </template>

      <el-button style="margin-left: 10px;" type="success" @click="submitUpload">Upload to OBS</el-button>
    </el-upload>

    <ElButton type="primary" class="mt-[60px]" @click="download">下载</ElButton>
  </div>
</template>
